<?php

declare(strict_types=1);

namespace MonologMysql\Handler;

use Monolog\Handler\AbstractProcessingHandler;
use Monolog\Logger;
use MonologMysql\Repository\RecordRepository;

class MysqlHandler extends AbstractProcessingHandler
{
    /** @var RecordRepository $recordRepository */
    protected RecordRepository $recordRepository;

    public function __construct(RecordRepository $recordRepository, $level = Logger::DEBUG, bool $bubble = true)
    {
        parent::__construct($level, $bubble);
        $this->recordRepository = $recordRepository;
    }

    protected function write(array $record): void
    {
        if (isset($record['formatted']) && !empty($record['formatted'])) {
            $data = $record['formatted'];
        } else {
            $data = $record;
        }
        $this->recordRepository->insert($data);
    }
}